layui.define(['jquery', 'form', 'tableSelect', 'upload'], function (exports) {
    var $ = layui.$,
        form = layui.form,
        upload = layui.upload,
        tableSelect = layui.tableSelect;

    form.verify({
        huo_shop: function(value, item){ //value：表单的值、item：表单的DOM对象
            var checked = $("input[name=action]:checked").val();
            if (checked == 1 && value == '') return '请选择活动商品';
        },
        huo_consume: function(value, item){ //value：表单的值、item：表单的DOM对象
            var checked = $("input[name=action]:checked").val();
            if (checked == 2 && value == '') return '请填写消耗积分';
            if (isNaN(value)) return '请填写数字';
        },
        huo_integral: function(value, item){ //value：表单的值、item：表单的DOM对象
            var name = $(item).data('name');
            var checked = $("input[name=" + name + "]:checked").val();
            if (checked == 1 && value == '') return '请填写赠送积分';
            if (isNaN(value)) return '请填写数字';
        },
        huo_coupon: function(value, item){ //value：表单的值、item：表单的DOM对象
            var name = $(item).data('name');
            var checked = $("input[name=" + name + "]:checked").val();
            if (checked == 2 && value == '') return '请选择优惠券';
        },
        huo_package: function(value, item){ //value：表单的值、item：表单的DOM对象
            var name = $(item).data('name');
            var checked = $("input[name=" + name + "]:checked").val();
            if (checked == 3 && value == '') return '请选择礼包';
        },
        huo_shop2: function(value, item){ //value：表单的值、item：表单的DOM对象
            var name = $(item).data('name');
            var checked = $("input[name=" + name + "]:checked").val();
            if (checked == 4 && value == '') return '请选择商品';
        }
    });

    //监听活动条件
    form.on('radio(action)', function(data){
        var value = data.value;
        $("#action .layui-form-item").eq(value-1).removeClass('layui-hide').siblings().addClass('layui-hide');
    });

    //监听赠送方式
    form.on('radio(song)', function(data){
        var value = data.value;
        $(this).parent().next().find('*').eq(value-1).removeClass('layui-hide').siblings().addClass('layui-hide');
    });

    //添加抽奖选项
    $("#add").click(function (){
        var index = $(".xuanxiang").length;
        $("#xuanxiang").append('<div class="layui-form-item xuanxiang">' +
            '<div class="layui-block" style="margin-left: 110px;">' +
            '<div class="layui-input-inline" style="width: 200px;">' +
            '<input type="text" name="xuan-name" lay-verify="required" placeholder="选项奖品名称" autocomplete="off" class="layui-input">' +
            '</div>' +
            '<div class="layui-input-inline" style="width: 200px;">' +
            '<input type="text" name="xuan-chance" lay-verify="required|number" placeholder="选项概率(%)" autocomplete="off" class="layui-input">' +
            '</div>' +
            '<button class="layui-btn  layui-btn-danger layui-btn-sm del">删除</button>' +
            '</div>' +
            '<div class="layui-block" style="margin-top: 20px;margin-left: 110px;">' +
            '<input type="text" name="img" lay-verify="required" style="width: 300px;display: inline-block;" placeholder="选项图片" autocomplete="off" class="layui-input">' +
            '<button style="margin-left: 15px;" type="button" class="layui-btn" id="up' + index + '">上传图片</button>' +
            '</div>' +
            '<div class="layui-block" style="margin-top: 10px;margin-left: 110px;">' +
            '<input type="radio" name="song' + index + '" value="1" lay-filter="song" title="赠送积分" checked>' +
            '<input type="radio" name="song' + index + '" value="2" lay-filter="song" title="赠送优惠券">' +
            '<input type="radio" name="song' + index + '" value="3" lay-filter="song" title="赠送礼包">' +
            '<input type="radio" name="song' + index + '" value="4" lay-filter="song" title="赠送商品">' +
            '<input type="radio" name="song' + index + '" value="5" lay-filter="song" title="无奖品">' +
            '</div>' +
            '<div class="layui-inline song-input' + index + '" style="margin-top: 10px;margin-left: 110px;">' +
            '<input type="text" name="integral" lay-verify="huo_integral" data-name="song' + index + '" placeholder="赠送积分" autocomplete="off" class="layui-input">' +
            '<input type="text" name="coupon_name" id="coupon' + index + '" lay-verify="huo_coupon" data-name="song' + index + '" placeholder="选择优惠券" autocomplete="off" class="layui-input layui-hide">' +
            '<input type="text" name="package_name" id="package' + index + '" lay-verify="huo_package" data-name="song' + index + '" placeholder="选择礼包" autocomplete="off" class="layui-input layui-hide">' +
            '<input type="text" name="shop_name" id="shop' + index + '" lay-verify="huo_shop2" data-name="song' + index + '" placeholder="选择商品" autocomplete="off" class="layui-input layui-hide">' +
            '<input type="hidden" name="coupon">' +
            '<input type="hidden" name="package">' +
            '<input type="hidden" name="shop">' +
            '</div>' +
            '</div>');
        form.render();
        openSelect('coupon', '#coupon' + index);
        openSelect('package', '#package' + index);
        openSelect('shop', '#shop' + index);
        upImg('#up' + index);
    });

    //生成IMG上传
    function upImg(demo){
        //普通图片上传
        upload.render({
            elem: demo
            ,url: '/admin/Activity/upload2'
            ,done: function(res){
                //如果上传失败
                if(res.code > 0){
                    return layer.msg('上传失败');
                }
                //上传成功
                layer.msg('上传成功');
                $(demo).prev().val(res.img);
            }
        });
    }

    //弹窗选择
    function openSelect(item, demo){
        var searchPlaceholder = '';
        var url = '';
        var cols = [[]];
        if (item === 'coupon'){
            searchPlaceholder = '搜索优惠券名称';
            url = '/admin/Product/coupon/status/2';
            cols = [[
                {type: 'radio'},
                {field: 'name', title: '优惠券名称', width: 400},
                {field: 'discount', title: '价值', width: 100, templet: function(d){
                    if (d.form == '0'){
                        return d.discount + '元';
                    }else{
                        return '订单总价的' + d.discount + '折';
                    }
                }},
                {field: 'limit', title: '领取限制', width: 100, templet: function(d){
                    if (d.limit == '0'){
                        return '不限';
                    }else{
                        return '限领' + d.limit + '份';
                    }
                }},
                {field: 'valid', title: '有效期', width: 100, templet: function(d){
                    if (d.limit == '0'){
                        return '不限';
                    }else{
                        return '限领' + d.limit + '份';
                    }
                }},
                {field: 'receive', title: '已领取', width: 100},
                {field: 'use', title: '已使用', width: 100},
            ]];
        } else if (item === 'package'){
            searchPlaceholder = '搜索大礼包名称';
            url = '/admin/Gift/package';
            cols = [[
                {type: 'radio'},
                {field: 'name', title: '大礼包名称', width: 400},
                {field: 'start', title: '有效期', width: 300, templet: function (d){ return formatDateTime(d.start) + '-' + formatDateTime(d.end) }}
            ]];
        } else if (item === 'shop'){
            searchPlaceholder = '搜索商品名称';
            url = '/admin/Product/product';
            cols = [[
                {type: 'radio'},
                {field: 'name', title: '商品名称', width: 400},
                {field: 'stock', title: '库存', width: 100},
                {field: 'volume', title: '销量', width: 100},
                {field: 'time', title: '添加时间', width: 200, templet: function(d){ return formatDateTime(d.time); }}
            ]];
        }
        tableSelect.render({
            elem: demo,	//定义输入框input对象
            checkedKey: 'id', //表格的唯一建值，非常重要，影响到选中状态 必填
            searchKey: 'name',	//搜索输入框的name值 默认keyword
            searchPlaceholder: searchPlaceholder,	//搜索输入框的提示文字 默认关键词搜索
            table: {	//定义表格参数，与LAYUI的TABLE模块一致，只是无需再定义表格elem
                url: url,
                method: 'post',
                cols: cols
            },
            done: function (elem, data) {
                //选择完后的回调，包含2个返回值 elem:返回之前input对象；data:表格返回的选中的数据 []
                //拿到data[]后 就按照业务需求做想做的事情啦~比如加个隐藏域放ID...
                var field = data.data;
                $(demo).val(field[0].name);
                $(demo).nextAll('input[name=' + item + ']').val(field[0].id);
            }
        });
    }

    //php时间戳用js转换为yyyy-mm-dd
    function formatDateTime(timeStamp) {
        var date = new Date();
        date.setTime(timeStamp * 1000);
        var y = date.getFullYear();
        var m = date.getMonth() + 1;
        m = m < 10 ? ('0' + m) : m;
        var d = date.getDate();
        d = d < 10 ? ('0' + d) : d;
        var h = date.getHours();
        h = h < 10 ? ('0' + h) : h;
        var minute = date.getMinutes();
        var second = date.getSeconds();
        minute = minute < 10 ? ('0' + minute) : minute;
        second = second < 10 ? ('0' + second) : second;
        return y + '-' + m + '-' + d+' '+h+':'+minute+':'+second;
    }

    //删除当前选项
    $(document).on('click', '.del', function (){
        $(this).parent().parent().remove();
    });

    exports('draw', {})
});